Page({
  data: {
    username: '',
    password: '',
    confirmPassword: '',
    email: '',
    phone: '',
    userTypes: ['普通用户', '维修工'],
    userTypeIndex: null
  },

  onInput(e) {
    const { field } = e.currentTarget.dataset
    this.setData({
      [field]: e.detail.value
    })
  },

  onUserTypeChange(e) {
    this.setData({
      userTypeIndex: e.detail.value
    })
  },

  async handleRegister() {
    const { username, password, confirmPassword, email, phone, userTypes, userTypeIndex } = this.data
    if (!username || !password || !confirmPassword || !email || !phone) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
      return
    }
    if (password !== confirmPassword) {
      wx.showToast({
        title: '两次密码不一致',
        icon: 'none'
      })
      return
    }
    if (userTypeIndex === null) {
      wx.showToast({
        title: '请选择注册用户类型',
        icon: 'none'
      })
      return
    }
    try {
      let requestUrl = `${getApp().globalData.baseUrl}/api/auth/register`;
      let postData = {
        username,
        password,
        email,
        phone,
        userType: userTypes[userTypeIndex]
      };
      // 新增：维修工注册逻辑
      if (userTypes[userTypeIndex] === '维修工') {
        requestUrl = `${getApp().globalData.baseUrl}/api/technicians/register`;
        postData = {
          name: username,
          password,
          email,
          phone,
          specialty: '家电维修'
        };
      }
      wx.request({
        url: requestUrl,
        method: 'POST',
        data: postData,
        header: {
          'Content-Type': 'application/json'
        },
        success: (res) => {
          if (res.statusCode === 200) {
            wx.showToast({
              title: '注册成功',
              icon: 'success'
            })
            setTimeout(() => {
              wx.redirectTo({ url: '/pages/login/login' })
            }, 1500)
          } else {
            wx.showToast({
              title: res.data.message || '注册失败',
              icon: 'none'
            })
          }
        },
        fail: (err) => {
          console.error('注册请求失败:', err);
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          })
        }
      })
    } catch (err) {
      console.error('注册过程中发生异常:', err);
      wx.showToast({
        title: err.message || '注册失败',
        icon: 'none'
      })
    }
  }
}) 